<template>
  <div :class="{ show: isShow }" class="header-search">
    <svg-icon
      id="guide-search"
      class-name="search-icon"
      icon="search"
      @click.stop="onShowClick"
    />
    <el-select
      ref="headerSearchSelectRef"
      class="header-search-select"
      v-model="search"
      filterable
      default-first-option
      remote
      placeholder="Search"
      :remote-method="querySearch"
      @change="onSelectChange"
    >
      <el-option
        v-for="option in searchOptions"
        :key="option.item.path"
        :label="option.item.title.join(' > ')"
        :value="option.item"
      ></el-option>
    </el-select>
  </div>
</template>

<script setup>
import { ref, computed, watch } from 'vue'
import { filterRoutes } from '@/utils/route'
import { useRouter } from 'vue-router'
import Fuse from 'fuse.js'
import { getData } from './FuseData'
import { watchLangChange } from '@/utils/i18n'
// 获取搜索数据源
const router = useRouter()
let searchRouter = computed(() => {
  return getData(filterRoutes(router.getRoutes()))
})
// 搜索
let searchFuse = null
const init = (searchRouter) => {
  searchFuse = new Fuse(searchRouter.value, {
    shouldSort: true,
    minMatchCharLength: 1,
    keys: [
      {
        name: 'title',
        weight: 0.7
      },
      {
        name: 'path',
        weight: 0.3
      }
    ]
  })
}
init(searchRouter)
// 搜索
const search = ref('')
const searchOptions = ref([])
const querySearch = (search) => {
  searchOptions.value = searchFuse.search(search)
}
const headerSearchSelectRef = ref(null)
// 控制显示
const isShow = ref(false)
const onShowClick = () => {
  headerSearchSelectRef.value.focus()
  isShow.value = !isShow.value
}

watch(isShow, (val) => {
  if (val) {
    document.body.addEventListener('click', onClose)
  } else {
    document.body.removeEventListener('click', onClose)
  }
})
const onClose = () => {
  headerSearchSelectRef.value.blur()
  isShow.value = false
  searchOptions.value = []
}
// 点击选项跳转
const onSelectChange = (item) => {
  router.push(item.path)
}

watchLangChange(() => {
  searchRouter = computed(() => {
    return getData(filterRoutes(router.getRoutes()))
  })
  init(searchRouter)
})
</script>

<style lang="scss" scoped>
.header-search {
  display: flex;
  align-items: center;
  font-size: 0 !important;
  .search-icon {
    cursor: pointer;
    font-size: 18px;
    vertical-align: middle;
  }
  .header-search-select {
    font-size: 18px;
    transition: width 0.2s;
    width: 0;
    overflow: hidden;
    background: transparent;
    border-radius: 0;
    display: inline-block;
    vertical-align: middle;

    ::v-deep .el-input__inner {
      border-radius: 0;
      border: 0;
      padding-left: 0;
      padding-right: 0;
      box-shadow: none !important;
      border-bottom: 1px solid #d9d9d9;
      vertical-align: middle;
    }
  }
  &.show {
    .header-search-select {
      width: 210px;
      margin-left: 10px;
    }
  }
}
</style>
